class UartHandler:
    def __init__(self, uart):
        self.uart = uart
        self.buffer = bytearray()
        self.last_receive_time = 0
        
    def data_available(self):
        return self.uart.any()
    
    def read_value(self):
        try:
            # 读取直到遇到换行符
            while self.uart.any():
                char = self.uart.read(1)
                if char == b'\n':
                    # 转换接收到的字符串为整数
                    value = int(self.buffer.decode())
                    self.buffer = bytearray()
                    # 发送ready应答
                    self.uart.write("ready\n".encode())
                    return value
                self.buffer.extend(char)
        except:
            self.buffer = bytearray()
            return None
        return None
    
    def send_ready(self):
        """发送ready信号"""
        try:
            self.uart.write("ready\n".encode())
        except:
            pass